import random
import re
from datetime import datetime

from flask import redirect
from flask import session

from flask import abort, jsonify
from flask import current_app
from flask import make_response
from flask import request
from flask import url_for

from info import constants, db
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.response_code import RET
from info import redis_store
from info.constants import IMAGE_CODE_REDIS_EXPIRES, SMS_CODE_REDIS_EXPIRES
from info.modules.passport import passport_blu
from info.utils.captcha.captcha import captcha


# get请求 访问格式127.0.0.1/news_list?cid=*&page=*，后端通过request.args获取传递的数据
@passport_blu.route('/image_code')
def get_image_code():
    # 读取请求
    imagecodeId = request.args.get("imageCodeId",None)
    if not imagecodeId:
        return abort(403)
    name,text,image = captcha.generate_captcha()

    try:
        redis_store.set("ImageCodeId" + imagecodeId,text,IMAGE_CODE_REDIS_EXPIRES)
    except Exception as ret:
        current_app.logger.debug(ret)
        abort(500)
    response = make_response(image)
    response.headers['Content-Type'] = "image/jpg"
    return response


@passport_blu.route('/passport/sms_code',methods = ['POST'])
def send_sms_code():
    # 请求数据格式为“{“mobile”："***"，“image_code”："***"，image_code_id："****"}”
    parameter_dict = request.json
    mobile = parameter_dict.get('mobile',None)
    image_code = parameter_dict.get('image_code', None)
    image_code_id = parameter_dict.get('image_code_id', None)
    if not all([parameter_dict]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    if re.match('1[35678]\\d{9}','mobile'):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号错误")
    try:
        real_code_id = redis_store.get("ImageCodeId"+image_code_id)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not real_code_id:
        return jsonify(errno=RET.NODATA, errmsg="图片已过期")
    if real_code_id.upper() != image_code.upper():
        return jsonify(errno=RET.DATAERR, errmsg="验证码错误")
    sms_code_str = "%06d" %random.randint(0,999999)
    print(sms_code_str)
    current_app.logger.debug("短信验证码是：%s" % sms_code_str)
    cpp = CCP()
    # 注意： 测试的短信模板编号为1
    result = cpp.send_template_sms(mobile,[sms_code_str,SMS_CODE_REDIS_EXPIRES/6],"1")
    # result =cpp.send_template_sms('18874173262', ['1234', 5], 1)
    if result != 0:
        return jsonify(errno=RET.THIRDERR, errmsg="发送失败")
    try:
        redis_store.set(mobile,sms_code_str,SMS_CODE_REDIS_EXPIRES)
    except Exception as ret:
        current_app.logger.debug(ret)
        current_app.loger.error('数据保存失败')
    return jsonify(errno=RET.OK, errmsg="发送成功")


@passport_blu.route('/passport/register',methods = ['POST'])
def register():
    # 请求数据格式为“{“mobile”："***"，“image_code”："***"，image_code_id："****"}”
    parameter_dict = request.json
    mobile = parameter_dict.get('mobile',None)
    smscode = parameter_dict.get('smscode', None)
    password = parameter_dict.get('password', None)
    if not all([parameter_dict]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    if re.match('1[35678]\\d{9}','mobile'):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号错误")
    try:
        real_code_id = redis_store.get(mobile)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not real_code_id:
        return jsonify(errno=RET.NODATA, errmsg="验证码已过期")
    if real_code_id.upper() != smscode.upper():
        return jsonify(errno=RET.DATAERR, errmsg="验证码错误")

    user = User()
    user.mobile = mobile
    user.nick_name = mobile
    user.last_login = datetime.now()
    user.password = password

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as ret:
        current_app.logger.error(ret)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    session['user_id'] = user.id
    return jsonify(errno=RET.OK, errmsg="登陆成功")


@passport_blu.route('/passport/login',methods=["post"])
def login():
    # 请求数据格式为“{“mobile”："***"，“image_code”："***"，image_code_id："****"}”
    # post请求格式  访问127.0.0.1/passport/login,后端通过request.json获取传递的数据
    parameter_dict = request.json
    mobile = parameter_dict.get('mobile',None)
    password = parameter_dict.get('passport', None)
    if not all([mobile,password]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    if re.match('1[35678]\\d{9}','mobile'):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号错误")

    try:
        user = User.query.filter(User.mobile==mobile).first()
    except Exception as ret:
        current_app.logger.debug(ret)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    if not user.check_passowrd(password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")

    user.last_login = datetime.now()
    try:
        db.session.commit()
    except Exception as ret:
        db.session.rollback()
        current_app.logger.debug(ret)

    session['user_id'] = user.id

    return jsonify(errno=RET.OK, errmsg="登陆成功")


@passport_blu.route('/passport/logout')
def logout():
    session.pop("user_id",None)
    return jsonify(errno=RET.OK, errmsg="退出成功")
    # return redirect(url_for('blu.index'))
    # 这里的“blu"为index视图函数所在的蓝图名 ，使用该方法需修改前端代码的href属性




